package com.szx.kaihei.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.RandomUtil;
import com.szx.kaihei.Enums.CaptchaType;
import com.szx.kaihei.constants.RedisConstant;
import com.szx.kaihei.exceptions.CustomException;
import com.szx.kaihei.exceptions.ExceptionEnums;
import com.szx.kaihei.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service

public class CodeServiceImpl implements CodeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SmsServiceImpl smsService;
    @Override
    public void getCode(String phone, CaptchaType type) {
            String code = RandomUtil.randomNumbers(4);
        boolean isSuccess = true;
        isSuccess =  stringRedisTemplate.opsForValue().setIfAbsent(type.getPrefix() + phone, code,RedisConstant.CODE_EXPIRE_TIME, TimeUnit.MILLISECONDS);

        if (!isSuccess){
            throw new CustomException(ExceptionEnums.USER_CODE_SEND_FREQUENTLY);
        }

        smsService.sendSms(phone, code);
    }

    @Override
    public boolean verifyCode(String phone, String code, CaptchaType type) {
        String redisCode = stringRedisTemplate.opsForValue().get(type.getPrefix() + phone);
        if (redisCode == null || !redisCode.equals(code)){
            return false;
        }
        return true;
    }

    /**
     * 获取图片验证码
     * @param phone
     * @param type
     */
    @Override
     public  String getCodeByImage(String phone, CaptchaType type) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 5);
        String code = lineCaptcha.getCode();
        stringRedisTemplate.opsForValue().set(RedisConstant.IMAGE_CODE + phone, code, RedisConstant.IMAGE_CODE_EXPIRE_TIME, TimeUnit.MILLISECONDS);
        return lineCaptcha.getImageBase64Data();
    }

    /**
     * 验证图片验证码
     * @param phone
     * @param code
     * @param type
     */
    @Override
    public boolean verifyCodeByImage(String phone, String code, CaptchaType type) {
        String redisCode = stringRedisTemplate.opsForValue().get(RedisConstant.IMAGE_CODE + phone);
        if (redisCode != null && redisCode.equalsIgnoreCase(code)){
            return true;
        }
        return false;
    }
}
